<?php

require_once 'MainPageWidget.php';
class TagsWidget extends MainPageWidget
{
	public $title = 'Облако тегов';

	public $tdi_oid;
	public $tag_class_name = "file";
	public $limit = 10;

	public $rq_tag = 'tag';

	public function Render()
	{
		if ($this->parent instanceof Action_Community_FeedHandler) {
			$this->rq_tag = $this->parent->rq_tag;
		}

		$db = $this->store->db;

		$community_oid = $this->getParam('community_oid', $this->acl_assistant->acl_data['comity_oid']);
		$tdi_oid = $this->getParam('tdi_oid');
		$tag = $this->getParam('tag');
		if ( !empty($community_oid) ) {
			$user_oid = $this->getParam('user_oid');
		} else {
			$user_oid = $this->acl_assistant->acl_data['user_url'];
		}
		$limit = $this->getParam('limit');
		
		$sql = "SELECT
								T.oid         AS oid,
								lower(T.name)        AS name,
								T.description AS description,
								COUNT(*)      AS `count`
						FROM
							store_objects AS O
							INNER JOIN store_class_tag AS T ON O.oid = T.oid
							                     AND "
							.(!empty($community_oid) ? "T.community_oid = {$db->quote($community_oid)}" : '1').
							"
							INNER JOIN store_tag_subject AS TS ON T.oid = TS.tag_oid
							INNER JOIN store_class_allfeed AS F ON F.oid  = TS.subject_oid
							                             AND F.is_deleted = 0
							INNER JOIN t_acl_tree AS TAT ON TAT.id_object = F.oid AND TAT.is_deleted = 0
						WHERE
							"
							.(!empty($community_oid) ? "F.community_oid = {$db->quote($community_oid)}" : '1')
							.(!empty($tdi_oid) ? " AND F.tdi_oid = {$db->quote($tdi_oid)} " : '')
							.(!empty($user_oid) ? " AND F.posted_by_id = {$db->quote($user_oid)} " : '')
							."
						GROUP BY lower(T.name)
						HAVING `count` > 0
						ORDER BY `count` DESC, name ASC
						"
						.($limit ? " LIMIT {$db->quote($limit)} " : '')
		;
		$rs = new DBStoreResult($this->store, $this->store->query($sql));
		$max_count = $min_count = NULL;
		// дергаем записи и кладем в массив $res,
		// считаем общее кол-во протегированных записей
		// считаем минимальное и максимальное кол-во записей по тегам
		$res = array();
		while ($obj = $rs->next()) {
			$t = $obj->data;
			$row = $rs->rs->current();
			$t['count'] = $row['count'];

			// ищем min и max количества тегов для облака
			if (isset($max_count)) {
				if ($t['count'] > $max_count) $max_count = $t['count'];
				if ($t['count'] < $min_count) $min_count = $t['count'];
			} else {
				$max_count = $min_count = $t['count'];
			}
			$res[] = $t;
		}
		// еще раз пробежимся по тегам и посчитаем вес каждого
		// а также установим флажки is_current (чтобы не бегать по 10 раз)
		$weights = 7; /* возможный диапазон весов [1..7] */
		$range = $max_count - $min_count;
		$filter = $this->getTagFilterParams();

		foreach ($res as &$item) {
			$c = $item['count'];
			$item['weight'] =
				($range) /* eсли есть разброс */
				? round(($c - $min_count) * ($weights - 1) / ($range)) + 1  /* м.б. от 1 до $weights */
				: round($weights / 2) /* иначе -- среднее */
				;

			$item['is_current'] = in_array($item['name'], $filter);
			$item['url'] = $this->hrefFilterByTag($item);
			if ( empty($item['url']) ) {
				$item['url'] = "?tag={$item['name']}";
			}
		}

		$content = array();
		$content['output_handler'] = "showfeed";
		$content['items'] = $res;
		$content['tdi_oid'] = $tdi_oid;

		$this->content = $content;

		return $this;
	}

	public function settingsForm ()
	{
		$config['form'] = array(
			'title' => 'Настройка списка меток',
			'fields' => array(

				'title' => array(
					'type' => 'text',
					'title' => 'Название',
					'default' => $this->title,
					'description' => 'Название виждета',
				),

				'limit' => array(
					'type' => 'text',
					'title' => 'Количество меток',
					'description' => 'Максимальное количесво меток в блоке',
					'default' => $this->limit,
				),
			),
		);
		return $config['form'];
	} // end of method settingsForm

	public function getTagFilterParams ()
	{
		if ($this->parent instanceof Action_Community_FeedHandler) {
			$res = $this->parent->getTagFilterParams($tag['name']);
		} else {
			$res = NULL;

			$GET = $this->ctx->rh->GET;
			if (isset($GET[$this->rq_tag])) {
				$params = $GET[$this->rq_tag];
				if (!is_array($params)) $params = array($params);
				$res = $params;
			}
		}
		return $res;
	} // end of method getDoctypeFilterParams
	public function hrefFilterByTag ($tag)
	{
		if ($this->parent instanceof Action_Community_FeedHandler) {
			$res = $this->parent->hrefFilterByTag($tag['name']);
		} else {
			$rule = 'showfeed';
			$rh = $this->ctx->rh;

			$this->ctx->rh->useClass('RL_URLGenerator');
			$ug = new RL_URLGenerator($rh->router->getRule($rule));
			$ug->setRouter($rh->router);
			$ug->setParams($this->params);
			$GET = $this->ctx->rh->GET;
			unset($GET[$this->rq_tag]);
			$ug->setGet(array_merge($GET, array($this->rq_tag=>$tag['name'])));
			$res = $ug->generateUrl();
		}
		return $res;
	} // end of method hrefFilterByTag
}

